<template>
  <div class="app-container" style="height:100%;">
    <!-- <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" class="bg-white p-1">
      <el-form-item label="字典名称" prop="dictType">
        <el-select v-model="queryParams.query.dictType" size="small">
          <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.dictName"
              :value="item.dictType"/>
        </el-select>
      </el-form-item>
      <el-form-item label="字典标签" prop="dictLabel">
        <el-input
            v-model="queryParams.query.dictLabel"
            placeholder="请输入字典标签"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8 my-1">
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:dict:add']"
        >新增
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="searchLoading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column label="字典标签" align="center" prop="dictLabel"/>
      <el-table-column label="字典键值" align="center" prop="dictValue"/>
      <el-table-column label="图标" align="center" prop="iconUrl" width="180">
        <template slot-scope="scope">
          <el-image v-if="scope.row.iconUrl" style="width: 40px; height: 40px" :src="imageUrlprefix + scope.row.iconUrl" lazy
                    :preview-src-list="scope.row.urlArr"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="字典排序" align="center" prop="sort"/>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:dict:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:dict:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"/> -->


    <myTableSearch
      ref="myTableSearchRef"
      :isOperate="true"
      :operateWidth="120"
      :titleName="$route.meta.title"
      :queryFn="getList"
      :formData="formData"
      :tableLabel="tableLabel"
      @recombinationData="recombinationData"
    >
      <template slot="tool">
        <div class="flex flex-x">
          <div class="fillBtn" @click="handleAdd" v-hasPermi="['system:user:add']">
            <img src="@/assets/images/gzq/icon-add.png" alt="" />
            <span>新增数据</span>
          </div>
        </div>
      </template>
      <template #createTime="scope">
        <span>{{ parseTime(scope.row.createTime) }}</span>
      </template>
      <template #iconUrl="scope">
        <el-image v-if="scope.row.iconUrl" style="width: 40px; height: 40px" :src="imageUrlprefix + scope.row.iconUrl" lazy
                    :preview-src-list="scope.row.urlArr"></el-image>
      </template>
      <template #dictType="scope">
        <span class="cursor" style="color:#30AAD1;border-bottom:1px solid #30AAD1" @click="toDictData(scope.row.dictType)">{{ scope.row.dictType }}</span>
      </template>
      <template slot="operate" slot-scope="scope">
        <div class="operateBtn flex">
          <div class="itemBtn" @click="handleUpdate(scope.row)" v-hasPermi="['system:dict:edit']">修改</div>
          <div class="itemBtn ml-1" @click="handleDelete(scope.row)" v-hasPermi="['system:dict:remove']">删除</div>
        </div>
      </template>
    </myTableSearch>

    <!-- 添加或修改参数配置对话框 -->
    <myDialog :isDialog="open" :title="title" :width="'500px'" @handleClose="cancel">
      <template slot="content">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="字典类型">
            <el-input v-model="form.dictType" :disabled="true"/>
          </el-form-item>
          <el-form-item label="数据标签" prop="dictLabel">
            <el-input v-model="form.dictLabel" placeholder="请输入数据标签"/>
          </el-form-item>
          <el-form-item label="数据键值" prop="dictValue">
            <el-input v-model="form.dictValue" placeholder="请输入数据键值"/>
          </el-form-item>
          <el-form-item label="图标" prop="iconUrl">
            <el-upload class="avatar-uploader" action :show-file-list="false" :http-request="imgUpload"
                      :before-upload="beforeUpload">
              <img v-if="form.iconUrl" :src="imageUrlprefix + form.iconUrl" class="avatar" style="width:148px;height:148px"/>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div style="color: black; text-align: center; width: 156px" v-if="form.iconUrl">点击图片更换</div>
          </el-form-item>
          <el-form-item label="显示排序" prop="sort">
            <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template slot="footer">
        <div class="formBtnBox">
          <div class="saveBtn" @click="submitForm">确 定</div>
          <div class="editBtn ml-4"  @click="cancel">取 消</div>
        </div>
      </template>
    </myDialog>
  </div>
</template>

<script>

import { dataPage,dataDeleteForce, dataDetail, dataAdd,dataUpdate } from "@/api/sys/dictData";
import { typeList} from "@/api/sys/dictType";
import {uploadFile, uploadRemove} from "@/api/upload/upload";

export default {
  name: "DictData",
  data() {
    return {
      formData: [
        {
          label: "字典名称",
          type: 'select',
          key: 'dictType',
          data: [],
          requestType: 'post',
          postName: typeList,
          optionLabel:'dictName',
          optionValue:'dictType',
          disabled:false,
        },
        {
          label: "字典类型",
          type: "input",
          key: "dictLabel",
        },
      ],
      tableLabel: [
        {
          prop: "dictLabel",
          label: "字典标签",
        },
        {
          prop: "dictValue",
          label: "字典键值",
        },
        {
          prop: "iconUrl",
          label: "图标",
        },
        {
          prop: "sort",
          label: "字典排序",
        },
        {
          prop: "remark",
          label: "备注",
        },
        {
          prop: "createTime",
          label: "创建时间",
        },
      ],
      defaultDictType:this.$route.query.dickType,
      total:0,
      searchLoading: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      selectedIds:[],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        query:{
          dictName: undefined,
          dictType:this.$route.query.dickType
        }
      },
      typeOptions:[],
      dataList:[],
      title:undefined,
      open:false,
      form:{},
      rules:{
        dictLabel: [
          { required: true, message: "数据标签不能为空", trigger: "blur" }
        ],
        dictValue: [
          { required: true, message: "数据键值不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "数据顺序不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    // this.getList();
    this.getTypeList();
  },
  mounted() {
    this.formData.forEach((item,index)=>{
      if(item.requestType=='post'){
        item.postName({}).then(res=>{
          if(res && res.code==200 && res.data){
            this.$set(item,'data',res.data)
          }
        })
      }
      if(item.key == 'dictType'){
        if(this.$route.query.dickType){
          item.value = this.$route.query.dickType
          item.disabled = true;
        }else{
          item.value = '';
          item.disabled = false;
        }
      }

    })
  },
  methods:{
    getList(e) {
      return dataPage(e)
    },
    //格式化搜索字段
    recombinationData(param, callback) {
      param = {
        dictType:this.$route.query.dickType||'',
        ...param,
      };
      callback({ ...param });
    },
    // getList(){
    //   this.searchLoading = true;
    //   dataPage(this.queryParams).then(response => {
    //     this.dataList = response.data.rows;
    //     this.dataList = this.dataList.map((item) => {
    //       item.urlArr = [];
    //       if (item.iconUrl) {
    //         item.urlArr.push(this.imageUrlprefix + item.iconUrl);
    //       }
    //       return item;
    //     })
    //     this.total = response.data.total;
    //     this.searchLoading = false;
    //   });
    // },
    getTypeList(){
      typeList({}).then(response => {
        this.typeOptions = response.data;
      });
    },
    handleQuery(){
      this.getList();
    },
    resetQuery(){
      this.resetForm("queryForm");
      this.queryParams.query.dictType = this.defaultDictType;
      this.handleQuery();
    },
    handleAdd(){
      this.reset();
      this.open = true;
      this.title = "添加字典类型";
      this.form.dictType = this.queryParams.query.dictType;
    },
    handleUpdate(row){
      this.reset();
      dataDetail(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改字典类型";
      });
    },
    handleDelete(row){
      const ids = row.id || this.selectedIds;
      this.$confirm('是否确认删除字典的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return dataDeleteForce(ids);
      }).then(() => {
        // this.getList();
        this.$refs.myTableSearchRef.searchReset();
        this.msgSuccess("删除成功");
      })
    },
    handleSelectionChange(selection){
      this.selectedIds = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    submitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            dataUpdate(this.form).then(() => {
              this.msgSuccess("修改成功");
              this.open = false;
              // this.getList();
              this.$refs.myTableSearchRef.searchReset();
            });
          } else {
            dataAdd(this.form).then(() => {
              this.msgSuccess("新增成功");
              this.open = false;
              // this.getList();
              this.$refs.myTableSearchRef.searchReset();
            });
          }
        }
      });
    },
    cancel(){
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dictLabel: undefined,
        dictValue: undefined,
        sort: 0,
        remark: undefined
      };
      this.resetForm("form");
    },
    imgUpload({file}) {
      if (this.form.iconUrl) {
        uploadRemove({url: this.form.iconUrl})
      }
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", "dict_icon");
      uploadFile(formData).then((res) => {
        if (res.code === 200) {
          this.form.iconUrl = res.data.url;
          this.$forceUpdate()
        }
      });
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/jpg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG JPEG PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
  }
}
</script>

<style scoped>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 146px;
  height: 146px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 146px;
  height: 146px;
  line-height: 146px;
  text-align: center;
}

.drawer_footer {
  display: flex;
  justify-content: flex-end;
}
</style>
